package com.hyper_yang._01_jdbc.dql;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DQLTest {

    @Test
    public void testQuery() throws Exception{
        // 注册驱动
        // 连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///test1", "root", "abc123");
        // 准备sql语句
//        String sql = "select * from t_account";
        // todo: SQL写完整，可以增加代码可读性
        String sql = "select id,name,balance from t_account";
        // 获取发射器
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 执行查询操作，获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        // 验证输出结果
        Assertions.assertTrue(resultSet.next(), "ResultSet is empty!");
        // 处理结果集，打印查询结果
        System.out.println("Query Results:");
        do {
            // todo: getXxx("列名") 也是为了提高代码可读性
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int balance = resultSet.getInt("balance");
            System.out.println("ID: " + id + ", Name: " + name + ", Balance: " + balance);
        } while (resultSet.next());
        // 释放资源
        preparedStatement.close();
        connection.close();
    }
}
